package 剑指Offer1;

import java.util.Stack;

public class _02包含min函数的栈 {
    class MinStack {
        private Stack<Integer> stack1;
        private Stack<Integer> stack2;


        /** initialize your data structure here. */
        public MinStack() {
            stack1 = new Stack<>();
            stack2 = new Stack<>();
        }

        public void push(int x) {
            stack1.push(x);
            if(stack2.isEmpty() || stack2.peek() >= x){ //更新最小值
                stack2.push(x);
            }
        }

        public void pop() {
            if(stack1.isEmpty() && stack2.isEmpty()) return;
            //如果栈1弹出来的元素和栈2栈顶元素相等，
            if(stack1.pop().equals(stack2.peek())){
                //说明弹出来的是最小元素，栈2也要弹出来
                stack2.pop();
            }
        }

        public int top() {
            if(stack1.isEmpty()) return -1;
            return stack1.peek();
        }

        public int min() {
            if(stack2.isEmpty()) return -1;
            return stack2.peek();
        }
    }
}
